package com.lizemin;

import cn.hutool.core.util.StrUtil;
import com.lizemin.annotations.DataScope;
import com.lizemin.entity.BaseEntity;
import com.lizemin.entity.Teacher;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author lzm
 * @date 2025/3/23 18:46
 * @description
 */
@Aspect
@Component
public class DataScopeAspect {

    @Autowired
    private HttpSession session;

    @Before("@annotation(dataScope)")
    public void around(JoinPoint pjp, DataScope dataScope) {
        Teacher teacher = (Teacher) session.getAttribute("user");
        String role = teacher.getRole();
        Object arg = pjp.getArgs()[0];
        if (!(arg instanceof BaseEntity)) {
            return;
        }
        StringBuilder sql = new StringBuilder();
        if (isHeadMaster(role)) {
            sql.append("1=1");
        } else {
            String dutyClass = teacher.getDutyClass();
            List<String> dutyCls = StrUtil.split(dutyClass, ",");
            if (!dutyCls.isEmpty()) {
                sql.append("class_name in (");
                for (String clazz : dutyCls) {
                    sql.append("'" + clazz + "',");
                }
                sql.deleteCharAt(sql.length() - 1);
                sql.append(")");
            } else {
                sql.append("1=0");
            }
        }
        BaseEntity param = (BaseEntity) arg;
        param.getParams().put("dataScope", sql.toString());
    }

    private boolean isHeadMaster(String role) {
        return StringUtils.equals("校长", role);
    }

}
